package cz.muni.fi.pv168.confusinglibrary.web;

import cz.muni.fi.pv168.confusinglibrary.database.DBUtils;
import cz.muni.fi.pv168.confusinglibrary.database.ServiceFailureException;
import cz.muni.fi.pv168.confusinglibrary.libs.Author;
import cz.muni.fi.pv168.confusinglibrary.libs.AuthorManagerDB;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
 *
 * @author Riema
 */
public class AuthorActionServerlet extends HttpServlet{
    private AuthorManagerDB authorManager = new AuthorManagerDB();
    private DataSource ds;

    @Resource(name = "jdbc/conflibrary")
    public void setDataSource(DataSource ds){
        authorManager.setDataSource(ds);
        this.ds = ds;
    }
    
    @Override
    public void init() throws ServletException{
        try{
            DBUtils.tryCreateTables(ds);
        }
        catch (SQLException ex){
            throw new ServiceFailureException("Error when trying to create tables", ex);
        }
    }

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        if (request.getServletPath().equals("/AddAuthor")){
            addAuthor(request, response);
        }
        else if (request.getServletPath().equals("/AllAuthors")){
            getAllAuthors(request, response);
        }
        else{
            throw new RuntimeException("Unknown operation: " + request.getServletPath());
        }

        //request.getRequestDispatcher("index.jsp").forward(request, response);

    }

    private void getAllAuthors(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        request.setAttribute("authors", authorManager.getAllAuthors());
        request.getRequestDispatcher("jsp/allAuthors.jsp").forward(request, response);
    }

    private void addAuthor(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
        if (request.getMethod().equals("POST")){
            Author author = new Author();
            String error = "";
            author.setName(request.getParameter("name").trim());
            try{
                author.setSurname(request.getParameter("surname").trim());
            }
            catch (IllegalArgumentException ex){
                error += "Surname is required. ";
            }
            try{
                author.setBorn(createDate(request.getParameter("born").trim()));
            }
            catch (ParseException ex){
                error += "Field born doesn't have correct formatting. ";
            }
            catch (IllegalArgumentException ex){
                error += "Born date isn't correct date. ";
            }
            try{
                author.setDied(createDate(request.getParameter("died").trim()));
            }
            catch (ParseException ex){
                error += "Field died doesn't have correct formatting. ";
            }
            catch (IllegalArgumentException ex){
                error += "Died date isn't correct date. ";
            }

            if (!error.equals("")){
                request.setAttribute("error", "Please correct following problems: " + error);
                request.setAttribute("author", author);
                request.setAttribute("born", request.getParameter("born").trim());
                request.setAttribute("died", request.getParameter("died").trim());
                request.getRequestDispatcher("jsp/addAuthor.jsp").forward(request, response);
            }
            else{
                authorManager.addAuthor(author);
                request.setAttribute("error", "Author has been successfully added.");
                request.setAttribute("author", new Author());
                request.getRequestDispatcher("jsp/addAuthor.jsp").forward(request, response);
                //response.sendRedirect(request.getContextPath());
            }
        }
        else{
            request.setAttribute("author", new Author());
            request.getRequestDispatcher("jsp/addAuthor.jsp").forward(request, response);
        }
    }

    private Date createDate(String stringDate) throws ParseException{
        if (stringDate.equals("")){
            return null;
        }
        SimpleDateFormat fmt = new SimpleDateFormat("dd-MM-yyyy");
        return fmt.parse(stringDate);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException{
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo(){
        return "Short description";
    }// </editor-fold>
}
